<script lang="ts" setup>
import { Delete, Edit } from "@element-plus/icons-vue";

import { ref, reactive, nextTick } from "vue";
import {
  SCOPE,
  type ComponentSize,
  FormInstance,
  FormRules,
  ElMessage,
} from "element-plus";
import {
  userGetAllService,
  userDeleteService,
  userSearchService,
  userAddService,
  userUpdateService,
  getUserById,
} from "../../utils/user.js";
import { el, id } from "element-plus/es/locale/index.js";
import { Value } from "sass";
import dayjs from "dayjs";
const formInline = reactive({
  userName: "",
});

const onSubmit = () => {
  console.log("submit!");
};

const userList = ref([]); //当前页数据
const allUsers = ref([]); // 全部用户数据
let total = ref(0); //全部页数

// 分页相关的状态

const currentPage = ref(1); //当前页
const pageSize = ref(5); //每页条数

const size = ref<ComponentSize>("default");
const background = ref(false);
const disabled = ref(false);
const updatePageData = () => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  userList.value = allUsers.value.slice(start, end);
};

const handleSizeChange = (val: number) => {
  pageSize.value = val;
  updatePageData();
};
//删除功能
const handleDelete = async (id) => {
  console.log(id);

  const confirmed = confirm("确定要删除此用户吗？"); // 确认删除
  if (confirmed) {
    const result = await userDeleteService(id); // 传递实际的用户 ID
    if (result) {
      console.log("用户已删除");
      gettableData(); // 重新获取用户数据
    } else {
      console.error("删除失败");
    }
  }
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  updatePageData();
};

const gettableData = async function () {
  let data = await userGetAllService();
  allUsers.value = data;
  total.value = data.length;

  updatePageData(); // 更新当前页的数据
  formInline.userName = "";

  for (let user of allUsers.value) {
    if (user && user.hasOwnProperty("Gender")) {
      console.log("user.Gender", user.Gender);

      // 检查 user 是否存在并且有 Gender 属性
      if (user.Gender === false) {
        user.Gender = "男";
      } else if (user.Gender === true) {
        user.Gender = "女";
      }
    }
  }
};

const searchUser = async function () {
  let data = await userSearchService(formInline.userName);
  allUsers.value = data;

  total.value = data.length;
  console.log(data);

  updatePageData(); // 更新当前页的数据

  for (let user of allUsers.value) {
    if (user && user.hasOwnProperty("Gender")) {
      console.log("user.Gender", user.Gender);

      // 检查 user 是否存在并且有 Gender 属性
      if (user.Gender === false) {
        user.Gender = "男";
      } else if (user.Gender === true) {
        user.Gender = "女";
      }
    }
  }
};

//添加会员

const dialogFormVisible = ref(false);
const formLabelWidth = "140px";

gettableData();
let form = reactive({
  userID: "",
  username: "",
  password: "",
  email: "",
  dateOfBirth: "",
  gender: "",
  repassword: "",
});
let forma = reactive({
  userID: "",
  username: "",
  password: "",
  email: "",
  dateOfBirth: "",
  gender: "",
  repassword: "",
});

//定义表单校验规则
const rules = reactive<FormRules>({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 2, max: 20, message: "用户名必须是 2-20位 的字符", trigger: "blur" },
    {
      // 自定义验证规则，确保用户名不包含任何数字
      validator: (rule, value, callback) => {
        const noDigitPattern = /^[^\d]*$/; // 匹配不包含任何数字的字符串
        if (!noDigitPattern.test(value)) {
          callback(new Error("用户名不能包含数字"));
        } else {
          callback(); // 验证通过
        }
      },
      trigger: "blur",
    },
  ],
  // 用户密码
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    {
      pattern: /^\S{6,15}$/,
      message: "密码必须是 6-15位 的非空字符",
      trigger: "blur",
    },
  ],
  // 再次输入密码
  repassword: [
    { required: true, message: "请输入密码", trigger: "blur" },
    {
      pattern: /^\S{6,15}$/,
      message: "密码必须是 6-15位 的非空字符",
      trigger: "blur",
    },
    {
      validator: (rule, value, callback) => {
        // 判断 value 和 当前 form 中收集的 password 是否一致
        if (value !== form.password) {
          callback(new Error("两次输入密码不一致"));
        } else {
          callback(); // 校验成功
        }
      },
      trigger: "blur",
    },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    {
      type: "email",
      message: "请输入正确的邮箱地址",
      trigger: "blur",
    },
  ],
});
const submitForm = async () => {
  await formRef.value?.validate().catch((err) => {
    ElMessage.error("注册失败");
    dialogFormVisible.value = false;
    throw err;
  });
  await userAddService(form);
  ElMessage.success("注册成功");
  gettableData();
  dialogFormVisible.value = false;
};
const formRef = ref<FormInstance>();

//编辑按钮
const Editdisabled = ref(false);

const EditsubmitForm = async () => {
  Editdisabled.value = false;
  formRef.value?.validate(async (valid) => {
    if (!valid) return;

    // 使用 dayjs 格式化日期
    const formattedDate = dayjs(form.dateOfBirth).format("YYYY-MM-DD");
    const dataToSubmit = { ...form, dateOfBirth: formattedDate };

    await userUpdateService(dataToSubmit);

    gettableData();
  });
};

//获取修改页面信息
const hendleEdit = async (id) => {
  try {
    const res = await getUserById(id); // 获取用户数据
    Editdisabled.value = true;
    Object.assign(form, res.data); // 合并数据
    form.gender = form.gender.toString(); // 转换性别为字符串
    console.log(form); // 输出当前数据
    gettableData();
  } catch (error) {
    console.error("获取用户信息失败", error);
  }
};
</script>


  

<template>
  <el-card style="box-card">
    <div class="card-header">
      <span>会员管理</span>
      <!-- 添加会员 -->
      <!--  -->
      <!--  -->
      <!--  -->
      <!--  -->
      <!--  -->
      <!--  -->

      <el-button plain @click="dialogFormVisible = true"> 添加会员 </el-button>
      <el-dialog v-model="dialogFormVisible" title="添加会员" width="500">
        <el-form :model="form" status-icon :rules="rules" ref="formRef">
          <!-- 姓名 -->
          <el-form-item
            label="用户姓名"
            :label-width="formLabelWidth"
            prop="username"
          >
            <el-input v-model="form.username" autocomplete="off" />
          </el-form-item>
          <!-- 用户密码 -->
          <el-form-item
            label="用户密码"
            :label-width="formLabelWidth"
            prop="password"
          >
            <el-input v-model="form.password" autocomplete="off" />
          </el-form-item>
          <!-- 确定密码 -->
          <el-form-item
            label="确定密码"
            :label-width="formLabelWidth"
            prop="repassword"
          >
            <el-input v-model="form.repassword" autocomplete="off" />
          </el-form-item>
          <!-- 邮箱 -->
          <el-form-item
            label="用户邮箱"
            :label-width="formLabelWidth"
            prop="email"
          >
            <el-input v-model="form.email" autocomplete="off" />
          </el-form-item>
          <!-- 性别 -->
          <el-form-item label="性别" :label-width="formLabelWidth">
            <el-radio-group v-model="form.gender">
              <el-radio value="1" size="large">男</el-radio>
              <el-radio value="0" size="large">女</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 出生日期 -->
          <el-form-item label="出生日期" :label-width="formLabelWidth">
            <div class="block">
              <el-date-picker
                v-model="form.dateOfBirth"
                type="date"
                placeholder="Pick a date"
              />
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm()"> 提交 </el-button>
          </div>
        </template>
      </el-dialog>
    </div>

    <div>
      <hr />
    </div>
    <!-- 搜索查询 -->
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="会员姓名" style="width: 300px">
        <el-input
          style="width: 240px"
          placeholder="请输入姓名要查询的姓名"
          v-model="formInline.userName"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="searchUser">搜索</el-button>
      </el-form-item>

      <el-form-item>
        <el-button type="default" @click="gettableData()">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="userList" style="width: 100%">
      <el-table-column prop="UserID" label="会员编号" />
      <el-table-column prop="Username" label="会员姓名" />
      <el-table-column prop="Email" label="会员邮箱" />
      <el-table-column prop="DateOfBirth" label="会员出生日期" />
      <el-table-column prop="Gender" label="性别" />

      <el-table-column label="操作" width="180">
        <template v-slot="scope">
          <!-- 编辑 -->
          <el-button
            type="primary"
            :icon="Edit"
            @click="hendleEdit(scope.row.UserID)"
            circle
          />

          <el-button
            type="danger"
            :icon="Delete"
            circle
            @click="handleDelete(scope.row.UserID)"
          />
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="Editdisabled" title="修改会员信息" width="500">
      <el-form :model="form" status-icon :rules="rules" ref="formRef">
        <!-- 姓名 -->
        <el-form-item
          label="用户姓名"
          :label-width="formLabelWidth"
          prop="username"
        >
          <el-input v-model="form.username" autocomplete="off" />
        </el-form-item>

        <!-- 用户密码 -->
        <el-form-item
          label="用户密码"
          :label-width="formLabelWidth"
          prop="password"
        >
          <el-input v-model="form.password" autocomplete="off" />
        </el-form-item>

        <!-- 邮箱 -->
        <el-form-item
          label="用户邮箱"
          :label-width="formLabelWidth"
          prop="email"
        >
          <el-input v-model="form.email" autocomplete="off" />
        </el-form-item>
        <!-- 性别 -->
        <el-form-item label="性别" :label-width="formLabelWidth">
          <el-radio-group v-model="form.gender">
            <el-radio value="0" size="large">男</el-radio>
            <el-radio value="1" size="large">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 出生日期 -->
        <el-form-item label="出生日期" :label-width="formLabelWidth">
          <div class="block">
            <el-date-picker
              v-model="form.dateOfBirth"
              type="date"
              placeholder="Pick a date"
              :default-value="new Date(2010, 9, 1)"
            />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="Editdisabled = false">取消</el-button>
          <el-button type="primary" @click="EditsubmitForm()"> 提交 </el-button>
        </div>
      </template>
    </el-dialog>

    <el-pagination
      class="el-p"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 15, 20]"
      :size="size"
      :disabled="disabled"
      :background="background"
      layout="jumper,total, sizes, prev, pager, next"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </el-card>
</template>


<style scoped>
.el-p {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.card-header {
  display: flex;
  justify-content: space-between;
}

.demo-date-picker {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
}
.demo-date-picker .block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
}
.demo-date-picker .block:last-child {
  border-right: none;
}
.demo-date-picker .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
</style>




